// Tool Registry Implementation

import {
    ToolRegistry,
    ToolDefinition,
    ToolHandler,
    RegisteredTool,
    ToolCategory
} from './interfaces';

/**
 * 工具注册表实现类
 */
export class DefaultToolRegistry implements ToolRegistry {
    private tools: Map<string, RegisteredTool> = new Map();
    private logger: any; // 简化的日志接口

    constructor(logger?: any) {
        this.logger = logger || console;
    }

    /**
     * 注册工具
     */
    register(toolName: string, definition: ToolDefinition, handler: ToolHandler): void {
        if (this.tools.has(toolName)) {
            this.logger.warn(`Tool '${toolName}' is already registered. Overwriting.`);
        }

        // 验证工具定义
        this.validateToolDefinition(definition);

        const registeredTool: RegisteredTool = {
            definition,
            handler,
            metadata: {
                registeredAt: new Date(),
                callCount: 0,
                lastCalled: null,
                isEnabled: true
            }
        };

        this.tools.set(toolName, registeredTool);
        this.logger.info(`Tool '${toolName}' registered successfully`);
    }

    /**
     * 注销工具
     */
    unregister(toolName: string): boolean {
        const existed = this.tools.has(toolName);
        if (existed) {
            this.tools.delete(toolName);
            this.logger.info(`Tool '${toolName}' unregistered successfully`);
        }
        return existed;
    }

    /**
     * 获取工具
     */
    getTool(toolName: string): RegisteredTool | null {
        return this.tools.get(toolName) || null;
    }

    /**
     * 获取所有工具
     */
    getAllTools(): RegisteredTool[] {
        return Array.from(this.tools.values());
    }

    /**
     * 按类别获取工具
     */
    getToolsByCategory(category: ToolCategory): RegisteredTool[] {
        return Array.from(this.tools.values()).filter(
            tool => tool.definition.category === category
        );
    }

    /**
     * 启用/禁用工具
     */
    setToolEnabled(toolName: string, enabled: boolean): boolean {
        const tool = this.tools.get(toolName);
        if (tool) {
            tool.metadata.isEnabled = enabled;
            this.logger.info(`Tool '${toolName}' ${enabled ? 'enabled' : 'disabled'}`);
            return true;
        }
        return false;
    }

    /**
     * 获取工具统计信息
     */
    getToolStats(toolName: string): any {
        const tool = this.tools.get(toolName);
        if (!tool) return null;

        return {
            name: toolName,
            category: tool.definition.category,
            callCount: tool.metadata.callCount,
            lastCalled: tool.metadata.lastCalled,
            isEnabled: tool.metadata.isEnabled,
            registeredAt: tool.metadata.registeredAt
        };
    }

    /**
     * 更新工具调用统计
     */
    updateCallStats(toolName: string): void {
        const tool = this.tools.get(toolName);
        if (tool) {
            tool.metadata.callCount++;
            tool.metadata.lastCalled = new Date();
        }
    }

    /**
     * 验证工具定义
     */
    private validateToolDefinition(definition: ToolDefinition): void {
        if (!definition.name || typeof definition.name !== 'string') {
            throw new Error('Tool name must be a non-empty string');
        }

        if (!definition.description || typeof definition.description !== 'string') {
            throw new Error('Tool description must be a non-empty string');
        }

        if (!Object.values(ToolCategory).includes(definition.category)) {
            throw new Error('Invalid tool category');
        }

        if (!Array.isArray(definition.parameters)) {
            throw new Error('Tool parameters must be an array');
        }

        // 验证参数定义
        for (const param of definition.parameters) {
            if (!param.name || typeof param.name !== 'string') {
                throw new Error('Parameter name must be a non-empty string');
            }

            const validTypes = ['string', 'number', 'boolean', 'object', 'array'];
            if (!validTypes.includes(param.type)) {
                throw new Error(`Invalid parameter type: ${param.type}`);
            }

            if (typeof param.required !== 'boolean') {
                throw new Error('Parameter required field must be a boolean');
            }
        }
    }

    /**
     * 清空所有工具
     */
    clear(): void {
        this.tools.clear();
        this.logger.info('All tools cleared from registry');
    }

    /**
     * 获取注册表大小
     */
    size(): number {
        return this.tools.size;
    }
}
